package com.h5ve.data.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Slf4j
@Component
public class StartupListener implements ApplicationListener<ApplicationReadyEvent> {
    private final Environment environment;

    public StartupListener(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            List<InetAddress> ipList = new ArrayList<>();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                // 过滤掉回环接口、未启用接口和虚拟接口
                if (networkInterface.isLoopback() || !networkInterface.isUp() || networkInterface.isVirtual()) {
                    continue;
                }
                // 获取网卡的所有 IP 地址
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = addresses.nextElement();
                    if (inetAddress instanceof java.net.Inet4Address) {
                         ipList.add(inetAddress);
                    }
                }
            }

            System.out.println("服务启动成功，访问地址:\n");
            String port = environment.getProperty("server.port", "8080");
            for (InetAddress inetAddress : ipList) {
                System.out.println("         🎉  http://" + inetAddress.getHostAddress() + ":" + port + " 🎉");
            }
        } catch (Exception e) {
            log.error("❌ 获取服务器地址失败: " + e.getMessage());
        }
    }
}
